package com.cip.admin.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.apache.struts2.ServletActionContext;

import com.cip.admin.model.Chat;
import com.cip.admin.model.Institute;
import com.cip.admin.model.User;
import com.cip.admin.service.InstituteService;
import com.cip.admin.service.RoleManager;
import com.cip.admin.service.UserManager;
import com.cip.common.util.CommonUtil;
import com.cip.common.util.SecurityUtil;
import com.cip.webapp.action.BaseAction;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


import net.sf.json.JSONObject;
/**
 * 
 * Class to create institute profile. it is master for all the packages.
 * 
 * @author vinoth
 *
 */
public class InstituteAction extends BaseAction {

	/**
	 * Default serialization id
	 */
	private static final long serialVersionUID = 1L;
	
	public static final Log logger = LogFactory.getLog(com.cip.admin.action.InstituteAction.class);
	
	private Institute institute;

	private List<Institute> instList;

	private InstituteService instituteService;
	
	private UserManager userManager;
	
	private RoleManager roleManager;
	
	private String instituteGridString;
	
	private List<File> files=new ArrayList<File>();
	

	public InstituteService getInstituteService() {
		return instituteService;
	}

	public void setInstituteService(InstituteService instituteService) {
		this.instituteService = instituteService;
	}	

	public UserManager getUserManager() {
		return userManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}	

	public RoleManager getRoleManager() {
		return roleManager;
	}

	public void setRoleManager(RoleManager roleManager) {
		this.roleManager = roleManager;
	}

	public String saveOrUpdateInstitute(){
		User loggedUser = SecurityUtil.getThreadLocalUser().get();
		try {
			institute.setTenantId(loggedUser.getTenantId());
			instituteService.saveOrUpdateInstitute(institute);	
			  // the directory to upload to
	       /* String uploadDir = ServletActionContext.getServletContext().getRealPath("/images")
	                + "/" + user.getTenantId()+ "/" + getRequest().getRemoteUser() + "/";
	       */ 
	        String uploadDir= ServletActionContext.getServletContext().getRealPath("/images") + "/" + "cip/banner"+"/"+institute.getPrefix()+File.separator;

	       int i=1;
	       System.out.println("files==============="+files.size());
	        for (File file: files) {
	        	String fileName="slide"+i+".jpg";
	        	System.out.println("================="+fileName);
	        	createFile(uploadDir, file,fileName);
		        i++;
		        if(i>6){
		        	break;
		        }
		    }

			saveMessage(getText("institute.added"));
		} catch (Exception e) {
			logger.error(getText("institute.saveError")+e.getMessage());
			addActionError(getText("institute.saveError")+e.getMessage());		
		} finally {
			try{
				User user = new User();
				user.setFirstName(institute.getInstituteName());
				user.setUsername(institute.getPrefix());
				user.setLastName("Admin");
				user.setPhoneNumber(institute.getPhoneNumber());
				user.setWebsite(institute.getWebsite());
				user.setPassword(institute.getPrefix());
				user.setEmail(institute.getEmailId());
				user.setEnabled(true);
				user.setTenantId(institute.getId());
				user.addRole(roleManager.getRole("ROLE_ADMIN"));
				userManager.saveUser(user);
			}catch (Exception e) {
				logger.error(getText("errors.existing.user")+e.getMessage()+" for the tenant "+loggedUser.getTenantId());
				//addActionError(getText("errors.existing.user")+e.getMessage());				
			}
	}
		return SUCCESS;
	}
	
	public void createFile(String path,File file,String fileName) throws IOException{
		
		  // write the file to the file specified
      File dirPath = new File(path);

      if (!dirPath.exists()) {
          dirPath.mkdirs();
      }

      //retrieve the file data
      InputStream stream = new FileInputStream(file);

      //write the file to the file specified
      OutputStream bos = new FileOutputStream(path + fileName);
      int bytesRead;
      byte[] buffer = new byte[8192];

      while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
          bos.write(buffer, 0, bytesRead);
      }

      bos.close();
      stream.close();
		
	}

	

	public String showInstList() throws Exception {
		//setInstList(instituteService.getAllInsList());
		Locale locale = getRequest().getLocale();
		System.out.println("local===================="+locale);
		String instituteString = instituteService.getInstGridList(locale);
		System.out.println("instArrayList================"+instituteString);
		
		getRequest().setAttribute("instituteGridString", instituteString);
		
		//setInstituteGridString(instituteString);
		
		return SUCCESS;
	}

	public String showEditInstitute() {
		try {
			setInstitute(instituteService.getInstituteById(institute.getId()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}	
	

	public String getInstituteGridString() {
		return instituteGridString;
	}

	public void setInstituteGridString(String instituteGridString) {
		this.instituteGridString = instituteGridString;
	}

	public String showInstitute() throws Exception {
		return SUCCESS;
	}


	public List<Institute> getInstList() {
		return instList;
	}

	public void setInstList(List<Institute> instList) {
		this.instList = instList;
	}

	public void setInstitute(Institute institute) {
		this.institute = institute;
	}

	public Institute getInstitute() {
		return institute;
	}

	public List<File> getFiles() {
		return files;
	}

	public void setFiles(List<File> files) {
		this.files = files;
	}
}
